<template>
  <div class="userlist">
    <!-- 筛选搜索功能 -->
    <SearchForm
      :currentLabel="currentLabel"
      :currentPlaceholder="currentPlaceholder"
      @submit-search="submitSearch"
    ></SearchForm>
    <!-- 添加数据列表 -->
    <addData>
      <template #btnText>
        <el-button type="primary">添加</el-button>
      </template>
    </addData>
    <!-- 数据表格 -->
    <el-table :data="state.list" border>
      <el-table-column label="编号" prop="id" align="center" width="50" />
      <el-table-column label="账号" prop="username" align="center" />
      <el-table-column label="姓名" prop="nickName" align="center" />
      <el-table-column label="邮箱" prop="email" align="center" />
      <el-table-column label="添加时间" prop="createTime" align="center">
        <template #default="scope">
          {{ moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column label="最后登录" prop="loginTime" align="center">
        <template #default="scope">
          {{
            scope.row.loginTime
              ? moment(scope.row.loginTime).format("YYYY-MM-DD HH:mm:ss")
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="是否启用" prop="status" align="center">
        <!-- scope.row可以用于接收每一行的所有值 -->
        <template #default="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            @change="changeUserStatus(scope.row)"
            v-model="scope.row.status"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="" align="center">
        <template #default="scope">
          <span class="role" @click="giveRoles(scope.row)">分配角色</span>
          <span class="edit" @click="edit(scope.row)">编辑</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <Pagination
      :total="total"
      :pageSize="pageSize"
      :currentPageNum="currentPageNum"
      :currentPageSize="currentPageSize"
      @changePageSize="changePageSize"
      @changePageNum="changePageNum"
    ></Pagination>
    <!-- 编辑框 -->
    <Edit
      @hideEdit="isHideEdit"
      @hideGiveRoles="isHideGiveRoles"
      @subEdit="subEdit"
      @subGiveRoles="subGiveRoles"
      @sub-register="subRegister"
      :isShowEdit="isShowEdit"
      :isShowGiveRoles="isShowGiveRoles"
      :userInfo="userInfo"
      :selectedRolesArr="selectedRolesArr"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs } from "vue";
import { FormInstance, ElMessage, ElMessageBox } from "element-plus";
/*
 * 网络请求接口
 */
import {
  getUserListApi,
  updateUserStatus,
  getUserRolesApi,
  addUserApi,
  searchUserApi,
} from "../../request/api";
import moment from "moment";
import { useStore } from "vuex";
/*
 * 组件
 */
import Edit from "../../components/Edit.vue";
import SearchForm from "../../components/SearchForm.vue";
import addData from "../../components/addData.vue";
import Pagination from "../../components/Pagination.vue";

/*
 * 定义数据
 */
const store = useStore();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  username: "",
});
// reactive定义的数据
const state = reactive({
  // 用于渲染表格的数据
  list: [{ status: 1, createTime: "", loginTime: "" }],
  // 传递给子组件的编辑页面数据
  userInfo: {
    username: "",
    nickName: "",
    email: "",
    password: "",
    note: "",
    status: 1,
    id: 1,
  },
  // 传递给子组件的渲染分配角色的数组
  selectedRolesArr: [""],
  pageSize: [10, 20, 30], // 分页插件选择一页显示n条数据的数组
  total: 0, // 列表数据总条数
  currentPageNum: 1, // 当前显示的是第几页
  currentPageSize: 10, // 当前一页显示n条数据
  currentLabel: "账号/姓名", // 传递给searchForm组件搜索框的label
  currentPlaceholder: "请输入账号、姓名", // 传递给searchForm组件搜索框的placeholder
});
let {
  userInfo,
  selectedRolesArr,
  pageSize,
  total,
  currentPageNum,
  currentPageSize,
  currentLabel,
  currentPlaceholder,
} = toRefs(state); // 解构出来，才能是响应式数据
// 分页插件数据
let isShowEdit = ref(false); // 是否显示弹出编辑框
let isShowGiveRoles = ref(false); // 是否显示分配角色框

/*
 * 声明方法
 *
 */

// 封装网络请求(数据)
const getUserList = (pageNum: number = 1, pageSize: number = 10) => {
  return new Promise((resolve, reject) => {
    getUserListApi({
      pageNum,
      pageSize,
    }).then(res => {
      if (res.code === 200) {
        console.log(res.data);
        state.list = res.data.list; // 存储表格数据
        // 存储分页插件需要的数据
        let { pageNum, pageSize, total, totalPage } = res.data;
        currentPageNum.value = pageNum;
        currentPageSize.value = pageSize;
        state.total = total;
        resolve(res.data);
      }
    });
  });
};

// 筛选搜索
const submitSearch = (keyword: string) => {
  searchUserApi(keyword).then(res => {
    if (res.code === 200) {
      console.log(res);
      // 更新分页器数据以及表格数据
      total.value = res.data.total;
      currentPageNum.value = res.data.pageNum;
      currentPageSize.value = res.data.pageSize;
      state.list = res.data.list;
    }
  });
};

// 添加用户
const subRegister = (userInfo: {}) => {
  // 发送网络请求
  addUserApi(userInfo).then(res => {
    if (res.code === 200) {
      console.log(res.data);
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      // 关闭编辑框
      isShowEdit.value = false;
    } else if (res.code === 500) {
      ElMessage({
        type: "error",
        message: "该用户已存在",
      });
    } else {
      ElMessage({
        type: "error",
        message: res.message,
      });
    }
  });
};

// 打开添加用户编辑框
const addUser = () => {
  // 打开编辑框
  isShowEdit.value = true;
  // 传递一个空对象（默认值）给子组件用于清空输入框
  userInfo.value = {
    username: "",
    nickName: "",
    email: "",
    password: "",
    note: "",
    status: 1,
    id: 1,
  };
};

// 修改用户status开关(是否启用)
const changeUserStatus = (info: { status: number; id: number }) => {
  updateUserStatus(info.id, info.status).then(res => {
    if (res.code === 200) {
      // 重新请求数据
      getUserList().then(() => {
        ElMessage({
          type: "success",
          message: "修改成功",
        });
      });
    }
  });
};

// 点击分配角色按钮(打开分配角色框)
const giveRoles = (info: userInfoItf) => {
  isShowGiveRoles.value = true;
  userInfo.value = info;
  getUserRolesApi(info.id).then(res => {
    if (res.code === 200) {
      console.log(res.data);
      let arr: string[] = [];
      // 将数据传递给子组件
      res.data.forEach(item => {
        arr.push(item.name);
      });
      selectedRolesArr.value = arr;
    }
  });
};

// 提交角色分配
const subGiveRoles = () => {
  isShowGiveRoles.value = false;
  // 重新请求数据
  getUserList().then(res => {
    isShowGiveRoles.value = false;
    ElMessage({
      type: "success",
      message: "修改成功",
    });
  });
};

// 关闭分配角色框(提交分配角色操作)
const isHideGiveRoles = () => {
  isShowGiveRoles.value = false;
};

// 点击编辑按钮(打开编辑框)
const edit = (obj: userInfoItf) => {
  userInfo.value = obj;
  isShowEdit.value = true;
};

// 提交编辑框
const subEdit = () => {
  isShowEdit.value = false;
  // 重新发送网络请求
  getUserList().then(() => {
    ElMessage({
      message: "修改成功",
      type: "success",
    });
  });
};

// 关闭编辑框
const isHideEdit = () => {
  isShowEdit.value = false;
};

// 分页功能按钮
// 改变页码
const changePageNum = (pageNum: number) => {
  currentPageNum.value = pageNum;
  getUserList(currentPageNum.value, currentPageSize.value);
};

// 改变一页显示n条
const changePageSize = (pageSize: number) => {
  currentPageSize.value = pageSize;
  getUserList(currentPageNum.value, currentPageSize.value);
};

// 查询搜索按钮
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      console.log("点击查询搜索按钮");
    } else {
      return false;
    }
  });
};

// 重置搜索表格
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 页面加载时，发送请求获取表格数据
getUserList();
</script>
<style lang="less" scoped>
.userlist {
  :deep(.cell) {
    font-size: 10px !important;
  }
  .role,
  .edit {
    cursor: pointer;
    color: #66b1ff;
  }
  .role {
    margin-right: 10px;
  }
  .demo-pagination-block {
    float: right;
    margin: 15px 0 0 0;
    :deep(.el-input__inner) {
      width: 125px !important;
    }
  }
}
</style>
